/**
 * @class Ext.app.PhieuBanHangPanel
 * @extends Ext.panel.Panel
 */
Ext.define('Ext.app.PhieuBanHangPanel', {
    extend: 'Ext.panel.Panel',
    alias: 'widget.phieuBanHangPanel',
    requires: [
        "Ext.app.MatHangTrongKhoLookup"
    ],

    initComponent: function () {
        Ext.apply(this, {
            autoScroll: true,
            border: true,
            layout: 'border',
            titleAlign: 'center',
            items: [
                {
                    region: 'north',
                    xtype: 'form',
                    layout: 'hbox',
                    bodyPadding: 5,
                    bodyStyle: 'background:#ECECEC',
                    items: [{
                        border: false,
                        bodyStyle: 'background:#ECECEC',
                        items: [{
                            xtype:'textfield',
                            fieldLabel: translations.get("HOME.TEN"),
                            labelWidth: 50,
                            maxLength: 200,
                            width: 350,
                            margin: '5 5 5 5',
                            anchor: '-5',
                            afterLabelTextTpl: required,
                            allowBlank: false,
                            name: 'customer'
                        }, {
                            xtype:'textfield',
                            fieldLabel: translations.get("HOME.DC"),
                            labelWidth: 50,
                            maxLength: 200,
                            width: 350,
                            margin: '5 5 5 5',
                            anchor: '-5',
                            afterLabelTextTpl: required,
                            allowBlank: false,
                            name: 'address'
                        }, {
                            xtype:'numberfield',
                            fieldLabel: translations.get("HOME.DAT_COC"),
                            hideTrigger: true,
                            fieldStyle: 'text-align:right',
                            minValue: 0,
                            allowDecimals: false,
                            labelWidth: 50,
                            maxLength: 200,
                            width: 350,
                            margin: '5 5 5 5',
                            anchor: '-5',
                            value: 0,
                            name: 'deposit'
                        }]
                    }, {
                        margin: '0 0 0 5',
                        border: false,
                        bodyStyle: 'background:#ECECEC',
                        items: [{
                            xtype:'textfield',
                            fieldLabel: translations.get("HOME.SDT"),
                            labelWidth: 50,
                            maxLength: 25,
                            margin: '5 5 5 5',
                            anchor: '100%',
                            name: 'phone'
                        },{
                            xtype:'textfield',
                            fieldLabel: translations.get("HOME.NVBH"),
                            labelWidth: 50,
                            maxLength: 200,
                            width: 350,
                            margin: '5 5 5 5',
                            afterLabelTextTpl: required,
                            allowBlank: false,
                            anchor: '100%',
                            name: 'seller'
                        },{
                            xtype: 'panel',
                            layout: 'hbox',
                            bodyStyle: 'background:#ECECEC',
                            border: false,
                            items: [
                                {
                                    xtype:'displayfield',
                                    fieldLabel: translations.get("HOME.DELIVERY_DATE"),
                                    afterLabelTextTpl: required,
                                    labelWidth: 120
                                },
                                {
                                    xtype:'datefield',
                                    format: 'd/m/Y',
                                    width: 100,
                                    value: new Date(),
                                    allowBlank: false,
                                    name: 'deliveryDate'
                                },
                                {
                                    xtype:'numberfield',
                                    hideTrigger: true,
                                    width: 30,
                                    minValue: 0,
                                    maxValue: 23,
                                    margin: '0 0 0 5',
                                    allowBlank: false,
                                    allowDecimals: false,
                                    name: 'deliveryHour'
                                },
                                {
                                    xtype:'displayfield',
                                    value: ':',
                                    margin: '0 5 0 5'
                                },
                                {
                                    xtype:'numberfield',
                                    hideTrigger: true,
                                    width: 30,
                                    minValue: 0,
                                    maxValue: 59,
                                    allowBlank: false,
                                    allowDecimals: false,
                                    name: 'deliveryMinute'
                                }
                            ],
                            margin: '5 5 5 5',
                            anchor: '100%'
                        }]
                    }]
                },
                {
                    region: 'center',
                    xtype: 'cell-editing',
                    columnLines: true,
                    viewConfig: {
                        markDirty: false
                    },
                    store: {
                        fields: ['stt', 'prodPK', 'tenMH', 'dvt', 'chieuDai', 'soTam', 'soLuong', 'donGia', 'thanhTien', 'ghiChu']
                    },
                    columns: [{ 
                        text: translations.get("HOME.STT"),
                        sortable: false,
                        draggable: false,
                        menuDisabled: true,
                        dataIndex: 'stt',
                        width: 50
                    },{
                        text: translations.get("HOME.TEN_HANG_HOA"),
                        sortable: false,
                        draggable: false,
                        menuDisabled: true,
                        dataIndex: 'tenMH',
                        flex: 1,
                        summaryRenderer: function(value, summaryData, dataIndex) {
                            return "T\u1ed5ng c\u1ed9ng";
                        }
                    },{
                        text: translations.get("HOME.DVT"),
                        sortable: false,
                        draggable: false,
                        menuDisabled: true,
                        dataIndex: 'dvt',
                        width: 50,
                        editor: new Ext.form.field.ComboBox({
                            allowBlank: false,
                            typeAhead: true,
                            store: [
                                ['Kg','Kg'],
                                [translations.get("HOME.MET"),translations.get("HOME.MET")]
                            ]
                        })
                    },{
                        text: translations.get("HOME.CHIEU_DAI"),
                        sortable: false,
                        draggable: false,
                        menuDisabled: true,
                        dataIndex: 'chieuDai',
                        align: 'right',
                        width: 80,
                        editor: new Ext.form.field.Number({
                            hideTrigger: true,
                            fieldStyle: 'text-align:right',
                            minValue: 0,
                            listeners: {
                                change: function(field, newValue, oldValue, eOpts) {
                                    var grid = field.up("cell-editing");
                                    var records = grid.getSelectionModel().getSelection();
                                    if(records.length == 1) {
                                        var soTam = records[0].get("soTam");
                                        if(soTam != null) {
                                            records[0].set("soLuong", soTam*newValue);
                                            var donGia = records[0].get("donGia");
                                            if(donGia != null) {
                                                records[0].set("thanhTien", donGia*soTam*newValue);
                                            }
                                        }
                                    }
                                }
                            }
                        }),
                        renderer: function(value) {
                            return formatNumber(value);
                        }
                    },{
                        text: translations.get("HOME.SO_TAM"),
                        sortable: false,
                        draggable: false,
                        menuDisabled: true,
                        dataIndex: 'soTam',
                        width: 80,
                        align: 'right',
                        editor: new Ext.form.field.Number({
                            hideTrigger: true,
                            fieldStyle: 'text-align:right',
                            minValue: 0,
                            listeners: {
                                change: function(field, newValue, oldValue, eOpts) {
                                    var grid = field.up("cell-editing");
                                    var records = grid.getSelectionModel().getSelection();
                                    if(records.length == 1) {
                                        var chieuDai = records[0].get("chieuDai");
                                        if(chieuDai != null) {
                                            records[0].set("soLuong", (chieuDai*newValue));
                                            var donGia = records[0].get("donGia");
                                            if(donGia != null) {
                                                records[0].set("thanhTien", donGia*chieuDai*newValue);
                                            }
                                        }
                                    }
                                }
                            }
                        }),
                        summaryType: 'sum',
                        renderer: function(value) {
                            return formatNumber(value);
                        }
                    },{
                        text: translations.get("HOME.SO_LUONG"),
                        sortable: false,
                        draggable: false,
                        menuDisabled: true,
                        dataIndex: 'soLuong',
                        align: 'right',
                        width: 80,
                        editor: new Ext.form.field.Number({
                            hideTrigger: true,
                            fieldStyle: 'text-align:right',
                            minValue: 0,
                            listeners: {
                                change: function(field, newValue, oldValue, eOpts) {
                                    var grid = field.up("cell-editing");
                                    var records = grid.getSelectionModel().getSelection();
                                    if(records.length == 1) {
                                        var donGia = records[0].get("donGia");
                                        if(donGia != null) {
                                            records[0].set("thanhTien", donGia*newValue);
                                        }
                                    }
                                }
                            }
                        }),
                        renderer: function(value) {
                            return formatNumber(value);
                        },
                        summaryType: 'sum'
                    },{
                        text: translations.get("HOME.DON_GIA"),
                        sortable: false,
                        draggable: false,
                        menuDisabled: true,
                        dataIndex: 'donGia',
                        align: 'right',
                        width: 150,
                        editor: new Ext.form.field.Number({
                            allowBlank: false,
                            hideTrigger: true,
                            allowDecimals: false,
                            fieldStyle: 'text-align:right',
                            minValue: 0,
                            listeners: {
                                change: function(field, newValue, oldValue, eOpts) {
                                    var grid = field.up("cell-editing");
                                    var records = grid.getSelectionModel().getSelection();
                                    if(records.length == 1) {
                                        var soLuong = records[0].get("soLuong");
                                        if(soLuong != null) {
                                            records[0].set("thanhTien", soLuong*newValue);
                                        }
                                    }
                                }
                            }
                        }),
                        renderer: function(value) {
                            return formatInteger(value);
                        }
                    },{
                        text: translations.get("HOME.THANH_TIEN"),
                        sortable: false,
                        draggable: false,
                        menuDisabled: true,
                        dataIndex: 'thanhTien',
                        width: 150,
                        align: 'right',
                        summaryType: 'sum',
                        renderer: function(value) {
                            return formatInteger(value);
                        }
                    },{
                        text: translations.get("HOME.GHI_CHU"),
                        sortable: false,
                        draggable: false,
                        menuDisabled: true,
                        dataIndex: 'ghiChu',
                        width: 150,
                        editor: {
                            allowBlank: true
                        }
                    }],
                    tbar: [
                        {
                            icon: 'images/add.png',
                            handler: function(button) {
                                var grid = button.up('cell-editing');
                                var newRecords = grid.getStore().getNewRecords();
                                var iLength = newRecords.length;
                                if(iLength >= 8) {
                                    Ext.MessageBox.alert('', translations.get("HOME.TOI_DA_8_MA_HANG"));
                                    return;
                                }
                                var win = Ext.create('widget.matHangTrongKhoLookup', {title: translations.get("HOME.CHON_MAT_HANG")});
                                win.setOpener(grid);
                                win.show();
                            }
                        },
                        '-',
                        {
                            text: translations.get("HOME.SAVE"),
                            icon: 'images/disk_blue.png',
                            handler: function(button) {
                                var panel = button.up('phieuBanHangPanel');
                                var form = panel.down('form');
                                if(!form.isValid()) {
                                    return;
                                }
                                var customer = form.down('[name=customer]').getValue();
                                var address = form.down('[name=address]').getValue();
                                var deposit = form.down('[name=deposit]').getValue();
                                var phone = form.down('[name=phone]').getValue();
                                var seller = form.down('[name=seller]').getValue();
                                var deliveryDate = panel.getDeliveryDate();

                                var grid = button.up('cell-editing');
                                grid.cellEditing.completeEdit();
                                var newRecords = grid.getStore().getNewRecords();
                                var iLength = newRecords.length;
                                if(iLength == 0) {
                                    Ext.MessageBox.alert('', translations.get("HOME.NHAP_MAT_HANG"));
                                    return;
                                }
                                if(!panel.isValid(grid.getStore())) {
                                    return;
                                }
                                var records = [];
                                for(var i=0;i<iLength; i++) {
                                    var r = newRecords[i];
                                    records.push({
                                        stt: r.get("stt"),
                                        prodPK: r.get("prodPK"),
                                        tenMH: r.get("tenMH"),
                                        dvt: r.get("dvt"),
                                        chieuDai: r.get("chieuDai"),
                                        soTam: r.get("soTam"),
                                        soLuong: r.get("soLuong"),
                                        donGia: r.get("donGia"),
                                        thanhTien: r.get("thanhTien"),
                                        ghiChu: r.get("ghiChu")
                                    });
                                }
                                var param = {
                                    customer: customer, 
                                    address: address,
                                    deposit: deposit,
                                    phone: phone,
                                    seller: seller,
                                    deliveryDate: deliveryDate,
                                    records: Ext.JSON.encode(records)
                                };
                                Ext.getBody().mask(translations.get("HOME.PLEASE_WAIT"));
                                Ext.Ajax.request({
                                    url: 'LuuPhieuBanHang.jsp',
                                    params: param,
                                    method: 'POST',
                                    success: function(response, opts) {
                                        Ext.getBody().unmask();
                                        var obj = Ext.decode(response.responseText);
                                        if(!obj.success) {
                                            showErrorMsg(obj.msg);
                                        }
                                        else {
                                            displayPanel({
                                                xtype: 'xemPhieuBanHangPanel',
                                                title: translations.get("HOME.PHIEU_BAN_HANG_TITLE") + " - " + obj.orderNo + " - " + obj.dateText
                                            });
                                            Ext.getCmp("xemPhieuBanHangPanel").setRecords(obj);
                                        }
                                    },
                                    failure: function(response, opts) {
                                        Ext.getBody().unmask();
                                        alert('server-side failure with status code ' + response.status);
                                    }
                                });
                            }
                        }
                    ],
                    onSelectRecord: function(record) {
                        this.addRow({
                            prodPK: record.prodPK,
                            prodCode: record.code,
                            tenMH: record.nameForSell,
                            dvt: translations.get("HOME.MET")
                        }, 3);
                    },
                    features: [{
                        ftype: 'summary',
                        dock: 'bottom'
                    }]
                }
            ]            
        });
        this.callParent(arguments);
    },
    
    isNullOrEmpty: function(value) {
        return (value == null || value == "");
    },

    isValid: function(store) {
        var iLength = store.getCount();
        for(var i=0; i<iLength; i++) {
            var record = store.getAt(i);
            if(this.isNullOrEmpty(record.get("tenMH"))) {
                Ext.MessageBox.alert('', translations.get("HOME.NHAP_MAT_HANG"));
                return false;
            }
            else if(this.isNullOrEmpty(record.get("soLuong"))) {
                Ext.MessageBox.alert('', translations.get("HOME.NHAP_SO_LUONG"));
                return false;
            }
            else if(this.isNullOrEmpty(record.get("donGia"))) {
                Ext.MessageBox.alert('', translations.get("HOME.NHAP_DON_GIA"));
                return false;
            }
        }
        return true;
    },
    
    lpad: function(value) {
        if(value == null || value == "") {
            value = "00";
        }
        value = value.toString();
        if(value.length == 1) {
            value = "0" + value;
        }
        return value;
    },
    
    getDeliveryDate: function() {
        var form = this.down('form');
        var deliveryDate = form.down('[name=deliveryDate]').getRawValue();
        if(deliveryDate == null || deliveryDate == "") {
            return "";
        }
        var deliveryHour = form.down('[name=deliveryHour]').getValue();
        deliveryDate += " " + this.lpad(deliveryHour);
        var deliveryMinute = form.down('[name=deliveryMinute]').getValue();
        deliveryDate += ":" + this.lpad(deliveryMinute);
        
        return deliveryDate;
    }
});
